package com.zoo.boot.component;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zoo.boot.api.CommonResult;
import com.zoo.boot.api.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 没有权限时返回json
 *
 * @Author: WangB
 * @Date: 2021/6/24
 */
public class CommonAccessDeniedHandler implements AccessDeniedHandler {

    private static final String _METHOD = "DELETE";

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        if (StrUtil.equals(_METHOD, request.getMethod())) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(CommonResult.fail(ResultCode.FORBIDDEN)));
        } else {
            //交回给SpringSecurity 进行处理，最终交给 SpringMvc 进行转发到错误页面
            response.sendError(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase());
        }


    }
}
